<?php

/**
 * Description of TestController
 *
 * @author Mi
 */
class QRController {

    private $DATA_PATH;
    private $DEFAULT_FILE;
    private $AUTH_DB;

    const NO_SUCH_USER = "-1";
    const WRONG_PW = "-2";
    const INVALID_TOKEN = "-3";
    const TOKEN_OK = "3";
    const NO_USER = "-4";
    const NO_TOKEN = "-5";
    const KEY_ALREADY_EXIST = "-6";
    const USER_ALREADY_EXIST = "-7";
    const NO_KEY = "-8";
    const NO_SUCH_KEY = "-9";
    const KEY_NOT_EXIST = "-10";
    const VIEW_DELETED = "5";
    const LAYOUT_DELETED = "6";
    const REGISTER_SUCCESS = "7";
    const EDIT_CREATE_VIEW_SUCCESS = "8";
    const WRITE_TO_KEY_SUCCESS = "9";
    const DELETE_VIEW_SUCCESS = "10";

    public function __construct($pwd) {
        $this->DATA_PATH = $pwd . '/data/';
        $this->DEFAULT_FILE = $this->DATA_PATH . "default.json";
        $this->AUTH_DB = $this->DATA_PATH . "accounts.json";
    }

    public function getAction(Request $request) {
        return $this->action($request);
    }

    public function postAction(Request $request) {
        return $this->action($request);
    }

    private function writeToKey($key, $content = NULL) {
        $alreadyExist = false;

        if (file_exists($this->DATA_PATH . $key)) {
            $alreadyExist = true;
        }

        $f = fopen($this->DATA_PATH . $key, "w+") or die("Konnte " . $this->DATA_PATH . $key . " nicht neuerstellen");

        if ($content == NULL) {
            $default = fopen($this->DEFAULT_FILE, "r");

            while ($line = fgets($default)) {
                fwrite($f, $line . "\n");
            }

            fclose($default);
        } else {
            fwrite($f, $content);
        }

        fclose($f);

        return QRController::WRITE_TO_KEY_SUCCESS;
    }

    public function action(Request $request) {
        try {
            if (isset($request->url_elements[2]) && $request->url_elements[2] == "load") {
                return $this->handleLOAD($request);
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "group") {
                if (isset($request->url_elements[3])) {
                    $key = $request->url_elements[3];

                    $f = fopen($this->DATA_PATH . $key, "w+") or die("Konnte " . $this->DATA_PATH . $key . " nicht öffnen");


                    fclose($f);

                    return $this->DATA_PATH . $key . " wurde erstellt/verändert";
                }
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "auth") {
                return $this->handleAUTH($request);
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "getlayouts") {
                return $this->handleGETLAYOUTS($request);
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "register") {
                return $this->handleREGISTER($request);
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "create") {
                return $this->handleCREATE($request);
            }else if (isset($request->url_elements[2]) && $request->url_elements[2] == "rename") {
                return $this->handleRENAME($request);
            }else if (isset($request->url_elements[2]) && $request->url_elements[2] == "edit") {
                return $this->handleEDIT($request);
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "deletelayout") {
                return $this->handleDELETELAYOUT($request);
            } else if (isset($request->url_elements[2]) && $request->url_elements[2] == "deleteview") {
                return $this->handleDELETEVIEW($request);
            }

            return "No Action match query: " . $request->query;
        } catch (Exception $e) {
            return "ERROR: " . $e->getMessage();
        }
    }

    private function useToken(Request $request) {
        if (isset($request->parameters['user'])) {
            if (isset($request->parameters['token'])) {
                $af = fopen($this->AUTH_DB, "r");
                $s = "";
                while ($line = fgets($af)) {
                    $s.=$line . "\n";
                }
                fclose($af);

                $accs = json_decode($s, true);

                if (!isset($accs[$request->parameters['user']])) {
                    return QRController::NO_SUCH_USER;
                }

                if ($accs[$request->parameters['user']]['token'] === $request->parameters['token']) {
                    $accs[$request->parameters['user']]['token'] = null;
                    $af = fopen($this->AUTH_DB, "w");
                    fwrite($af, json_encode($accs));
                    fclose($af);
                    return QRController::TOKEN_OK;
                } else {
                    
                }
            } else {
                return QRController::NO_TOKEN;
            }
        } else {
            return QRController::NO_USER;
        }
    }

    private function handleREGISTER(Request $request) {
        if (isset($request->parameters['user']) && isset($request->parameters['pw'])) {
            $af = fopen($this->AUTH_DB, "r");
            $s = "";
            while ($line = fgets($af)) {
                $s.=$line . "\n";
            }
            fclose($af);
            $accs = json_decode($s, true);

            if (!isset($accs[$request->parameters['user']])) {
                //der name scheint noch frei zu sein
                $accs[$request->parameters['user']] = array(
                    'pw' => $request->parameters['pw'],
                    'token' => NULL,
                    'layouts' => array()
                );

                $af = fopen($this->AUTH_DB, "w");
                fwrite($af, json_encode($accs));
                fclose($af);
                return QRController::REGISTER_SUCCESS;
            } else {
                return QRController::USER_ALREADY_EXIST;
            }
        }
    }

    private function handleAUTH(Request $request) {
        if (isset($request->parameters['user']) && isset($request->parameters['pw'])) {
            //Check ob user+pw stimmen
            $af = fopen($this->AUTH_DB, "r");
            $s = "";
            while ($line = fgets($af)) {
                $s.=$line . "\n";
            }
            fclose($af);



            $accs = json_decode($s, true);
            if (isset($accs[$request->parameters['user']])) {
                if ($accs[$request->parameters['user']]['pw'] === $request->parameters['pw']) {
                    $token = $request->parameters['user'] . time() . $request->parameters['pw'];
                    $token = md5($token);
                    $accs[$request->parameters['user']]['token'] = $token;

                    $af = fopen($this->AUTH_DB, "w");
                    fwrite($af, json_encode($accs));
                    fclose($af);

                    return $token;
                } else {
                    return QRController::WRONG_PW;
                }
            } else {

                return QRController::NO_SUCH_USER;
            }
        }
    }

    private function handleCREATE(Request $request) {
        if (isset($request->parameters['user'])) {
            if (isset($request->parameters['token'])) {
                if (isset($request->parameters['key'])) {
                    if (isset($request->parameters['name'])) {
                    
                        //Ok alles ist da, wir können anfangen
                        if (!file_exists($this->DATA_PATH . $request->parameters['key'])) {
                            $isTokenCorrect = $this->useToken($request);
                            if ($isTokenCorrect === QRController::TOKEN_OK) {
                                //Token ist gültig letze gooooo

                                $af = fopen($this->DEFAULT_FILE, "r");
                                $default = "";
                                while ($line = fgets($af)) {
                                    $default.=$line . "\n";
                                }
                                fclose($af);

                                $json = json_decode($default, true);            
                                $json['user'] = $request->parameters['user'];
                                $json['name'] = $request->parameters['name'];

                                if($this->writeToKey($request->parameters['key'], json_encode($json)) == QRController::WRITE_TO_KEY_SUCCESS){
                                    $f = fopen($this->AUTH_DB, "r");
                                    $data = "";
                                    while ($line = fgets($f)) {
                                        $data.=$line . "\n";
                                    }
                                    fclose($f);

                                    $accs = json_decode($data, true);
                                    $user = $accs[$request->parameters['user']];
                                    $l = $user['layouts'];
                                    $l[] = $request->parameters['key'];
                                    $user['layouts'] = $l;
                                    $accs[$request->parameters['user']] = $user;
                                    
                                    $af = fopen($this->AUTH_DB, "w");
                                    fwrite($af, json_encode($accs));
                                    fclose($af);
                                    return QRController::WRITE_TO_KEY_SUCCESS;
                                }
                            } else {
                                //Irgendwas stimmt mit dem Token nich
                                return $isTokenCorrect;
                            }
                        } else {
                            return QRController::KEY_ALREADY_EXIST;
                        }
                    
                    
                    }
                    
                }
            }
        }
    }
    
        private function handleRENAME(Request $request) {
        if (isset($request->parameters['user'])) {
            if (isset($request->parameters['token'])) {
                if (isset($request->parameters['key'])) {
                    if (isset($request->parameters['name'])) {
                    
                        //Ok alles ist da, wir können anfangen
                        if (file_exists($this->DATA_PATH . $request->parameters['key'])) {
                            $isTokenCorrect = $this->useToken($request);
                            if ($isTokenCorrect === QRController::TOKEN_OK) {
                                //Token ist gültig letze gooooo

                                $af = fopen($this->DATA_PATH . $request->parameters['key'], "r");
                                $data = "";
                                while ($line = fgets($af)) {
                                    $data.=$line . "\n";
                                }
                                fclose($af);

                                $json = json_decode($data, true);
                                $json['name'] = $request->parameters['name'];

                                return $this->writeToKey($request->parameters['key'], json_encode($json));
                            } else {
                                //Irgendwas stimmt mit dem Token nich
                                return $isTokenCorrect;
                            }
                        } else {
                            return QRController::KEY_ALREADY_EXIST;
                        }
                    
                    
                    }
                    
                }
            }
        }
    }

    private function handleEDIT(Request $request) {
        if (isset($request->parameters['user'])) {
            if (isset($request->parameters['token'])) {
                if (isset($request->parameters['key'])) {
                    if (isset($request->parameters['json'])) {
                        //Ok alles ist da, wir können anfangen
                        if (file_exists($this->DATA_PATH . $request->parameters['key'])) {
                            $isTokenCorrect = $this->useToken($request);
                            if ($isTokenCorrect === QRController::TOKEN_OK) {
                                //Token ist gültig letze gooooo
                                $this->writeToKey($request->parameters['key'], $request->parameters['json']);
                                return QRController::EDIT_CREATE_VIEW_SUCCESS;
                            } else {
                                //Irgendwas stimmt mit dem Token nich
                                return $isTokenCorrect;
                            }
                        } else {
                            return QRController::KEY_NOT_EXIST;
                        }
                    }
                }
            }
        }
    }

    private function handleLOAD(Request $request) {
        if (isset($request->url_elements[3])) {
            $key = $request->url_elements[3];


            if (file_exists($this->DATA_PATH . $key)) {
                $f = fopen($this->DATA_PATH . $key, "r");

                $data = "";
                while (!feof($f)) {
                    $data .= fgets($f) . "\n";
                }

                fclose($f);

                return $data;
            } else {
                return QRController::NO_SUCH_KEY;
            }
        } else {
            return QRController::NO_KEY;
        }
    }

    private function handleDELETELAYOUT(Request $request) {
        if (isset($request->parameters['user'])) {
            if (isset($request->parameters['token'])) {
                if (isset($request->parameters['key'])) {
                    //Ok alles ist da, wir können anfangen
                    if (file_exists($this->DATA_PATH . $request->parameters['key'])) {
                        $isTokenCorrect = $this->useToken($request);
                        if ($isTokenCorrect === QRController::TOKEN_OK) {
                            //Token ist gültig letze gooooo
                            unlink($this->DATA_PATH . $request->parameters['key']);
                            $f = fopen($this->AUTH_DB, "r+");
                            $data = "";
                            while (!feof($f)) {
                                $data .= fgets($f) . "\n";
                            }
                            fclose($f);

                            $json = json_decode($data, true);
                            $user = $json[$request->parameters['user']];
                            $layouts = $user['layouts'];
                            $newLayouts = array();
                            for ($i = 0; $i < count($layouts); $i++) {
                                if ($layouts[$i] !== $request->parameters['key']) {
                                    $newLayouts[] = $layouts[$i];
                                }
                            }
                            $user['layouts'] = $newLayouts;
                            $json[$request->parameters['user']] = $user;

                            $f = fopen($this->AUTH_DB, "w");
                            fwrite($f, json_encode($json));
                            fclose($f);

                            return QRController::LAYOUT_DELETED;
                        } else {
                            //Irgendwas stimmt mit dem Token nich
                            return $isTokenCorrect;
                        }
                    } else {
                        return QRController::KEY_NOT_EXIST;
                    }
                }
            }
        }
    }

    private function handleDELETEVIEW(Request $request) {
        if (isset($request->parameters['user'])) {
            if (isset($request->parameters['token'])) {
                if (isset($request->parameters['key'])) {
                    if (isset($request->parameters['view'])) {
                        //Ok alles ist da, wir können anfangen
                        if (file_exists($this->DATA_PATH . $request->parameters['key'])) {
                            $isTokenCorrect = $this->useToken($request);
                            if ($isTokenCorrect === QRController::TOKEN_OK) {
                                //Token ist gültig letze gooooo
                                $f = fopen($this->DATA_PATH . $request->parameters['key'], "r");
                                $data = "";
                                while (!feof($f)) {
                                    $data .= fgets($f) . "\n";
                                }
                                fclose($f);
                                
                                $json = json_decode($data, true);
                                $views = $json['views'];
                                
                                $newViews = array();
                                $invert = "---";
                                for ($i = 0; $i < count($views); $i++) {
                                    if ($views[$i]['name'] != $request->parameters['view']) {
                                        $newViews[] = $views[$i];
                                        $invert = $views[$i];
                                    }
                                }
                                $json['views'] = $newViews;

                                if($this->writeToKey($request->parameters['key'], json_encode($json)) === QRController::WRITE_TO_KEY_SUCCESS){
                                    return QRController::DELETE_VIEW_SUCCESS;
                                }
                            } else {
                                //Irgendwas stimmt mit dem Token nich
                                return $isTokenCorrect;
                            }
                        } else {
                            return QRController::KEY_NOT_EXIST;
                        }
                    }
                }
            }
        }
    }

    private function handleGETLAYOUTS(Request $request) {
        if (isset($request->url_elements[3])) {
            $user = $request->url_elements[3];

            $f = fopen($this->AUTH_DB, "r");

            $data = "";
            while (!feof($f)) {
                $data .= fgets($f) . "\n";
            }

            fclose($f);

            $accs = json_decode($data, true);

            if (isset($accs[$user])) {
                return json_encode($accs[$user]['layouts']);
            } else {
                return QRController::NO_SUCH_USER;
            }
        } else {
            return QRController::NO_KEY;
        }
    }

}

?>
